// ******************************************************************
// * Copyright(c)  Steven Lu
// * Description   : Entity_MST_SUPPLIER
// * CreateDate    : 2011/8/16 10:16:40
// * Creater       : CodeSmith
// * LastChangeDate: 2011/8/16 10:16:40
// * LastChanger   : 2011/8/16 10:16:40
// * Version Info  : 1.0 For ESOL
// ******************************************************************

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Suzsoft.Smart.Data;
using ESOL.Common.Entity;
using ESOL.Common;

namespace ESOL.Business.Mst
{
/// <summary>
    /// MstSupplier
    /// </summary>
    public partial class MstSupplierBs
    {
        #region GetByID
        /// <summary>
        /// Get Entity
        /// </summary>
        /// <param name="objMstSupplierEntity">Entity</param>
        /// <returns>Entity</returns>
        public static MstSupplierEntity GetMstSupplier(MstSupplierEntity objMstSupplierEntity)
        {
            return DataAccess.SelectSingle<MstSupplierEntity>(objMstSupplierEntity);
        }

        public static MstSupplierEntity GetMstSupplierById(string supplierId)
        {
            if (string.IsNullOrEmpty(supplierId))
            {
                return null;
            }
            MstSupplierEntity objMstSupplierEntity = new MstSupplierEntity();
            objMstSupplierEntity.SupplierId = supplierId;
            return DataAccess.SelectSingle<MstSupplierEntity>(objMstSupplierEntity);
        }

        public static MstSupplierEntity GetByImportOrder(string importOrderId)
        {
            if (string.IsNullOrEmpty(importOrderId))
            {
                return null;
            }
            string sql = @"SELECT DISTINCT S.*
                            FROM MST_SUPPLIER S
                            INNER JOIN PUR_PURCHASE_ORDER PO ON PO.SUPPLIER_ID = S.SUPPLIER_ID
							INNER JOIN PUR_PURCHASE_ORDER_ITEM POI ON POI.PURCHASE_ORDER_ID = PO.PURCHASE_ORDER_ID
							INNER JOIN PUR_PURCHASE_ARRIVED_ITEM PAI ON PAI.PURCHASE_ITEM_ID = POI.PURCHASE_ITEM_ID
                            INNER JOIN INV_IMPORT_ORDER IIO ON IIO.RELATED_ORDER = PAI.ARRIVED_ID
                            WHERE IIO.IMPORT_ORDER_ID = '" + importOrderId + "'";
            List<MstSupplierEntity> list = DataAccess.Select<MstSupplierEntity>(sql);
            if (list != null && list.Count > 0)
            {
                return list[0];
            }
            return null;
        }
        #endregion

        #region Insert
        /// <summary>
        /// Insert Data
        /// </summary>
        /// <param name="objMstSupplierEntity">Entity</param>
        /// <returns>true Insert Succeed; false Insert Fail</returns>
        public static bool InsertMstSupplier(MstSupplierEntity objMstSupplierEntity)
        {
            return DataAccess.Insert(objMstSupplierEntity);
        }

        public static bool InsertMstSupplier(List<MstSupplierEntity> objMstSupplierEntityList)
        {
            return DataAccess.Insert(objMstSupplierEntityList);
        }
        #endregion

        #region Update
        /// <summary>
        /// Update Data
        /// </summary>
        /// <param name="objMstSupplierEntity">Entity</param>
        /// <returns>true Update Succeed; false Update Fail</returns>
        public static bool UpdateMstSupplier(MstSupplierEntity objMstSupplierEntity)
        {
            return DataAccess.Update(objMstSupplierEntity);
        }

        public static bool UpdateMstSupplier(List<MstSupplierEntity> objMstSupplierEntityList)
        {
            return DataAccess.Update<MstSupplierEntity>(objMstSupplierEntityList);
        }
        #endregion

        #region Delete
        /// <summary>
        /// Delete Data
        /// </summary>
        /// <param name="objMstSupplierEntity">Entity</param>
        /// <returns>true Delete Succeed; false Delete Fail</returns>
        public static bool DeleteMstSupplier(MstSupplierEntity objMstSupplierEntity)
        {
            return DataAccess.Delete(objMstSupplierEntity);
        }

        public static bool DeleteMstSupplier(List<MstSupplierEntity> objMstSupplierEntityList)
        {
            return DataAccess.Delete<MstSupplierEntity>(objMstSupplierEntityList);
        }
        #endregion

        #region GetAll
        /// <summary>
        /// Get All Data
        /// </summary>
        /// <returns>Back All Data<returns>
        public static DataSet GetMstSupplierAll()
        {
            return DataAccess.SelectAllDataSet<MstSupplierEntity>();
        }
        /// <summary>
        /// Get All Data List
        /// </summary>
        /// <returns>Back All Data List<returns>
        public static List<MstSupplierEntity> GetMstSupplierAllList()
        {
            return DataAccess.SelectAll<MstSupplierEntity>();
        }
        #endregion

        #region GetByCondition
        public static DataTable GetMstSupplierByCondition(string rowCount,string condition, string orderBy)
        {
            string sql = CommonFunctions.GetSelect(rowCount) + @"S.*, CASE WHEN A.SUPPLIER_ID IS NULL THEN 0 ELSE 1 END AS IS_EXPIRED
                            FROM MST_SUPPLIER S
                            LEFT JOIN (
	                            SELECT SUPPLIER_ID FROM MST_SUPPLIER_ATTACHED WHERE EXPIRED_DATE <= GETDATE() 
	                            GROUP BY SUPPLIER_ID
                            ) A ON S.SUPPLIER_ID = A.SUPPLIER_ID
                            WHERE S.STATUS != 'STATUS05' ";
            if (string.IsNullOrEmpty(condition) == false)
            {
                sql += condition;
            }
            if (string.IsNullOrEmpty(orderBy) == false)
            {
                sql += " ORDER BY " + orderBy;
            }
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null && ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return null;
        }
        #endregion

        #region Functions
        private static string GetNextSupplierCode()
        {
            string nextSupplierCode = "S001";
            string sql = "SELECT MAX(SUPPLIER_CODE) AS SUPPLIER_CODE FROM MST_SUPPLIER";
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                nextSupplierCode = ds.Tables[0].Rows[0]["SUPPLIER_CODE"].ToString();
            }
            if (string.IsNullOrEmpty(nextSupplierCode) || CommonFunctions.IsNumeric(nextSupplierCode.Replace("S","")) == false)
            {
                return "S001";
            }
            nextSupplierCode = "S" + (Convert.ToInt32(nextSupplierCode.Replace("S","")) + 1).ToString().PadLeft(3,'0');
            return nextSupplierCode;
        }
        public static bool SaveSupplier(bool isNew, MstSupplierEntity supplier, DataTable dtDetail, List<MstSupplierContactEntity> deleteList)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    if (isNew)
                    {
                        supplier.SupplierCode = GetNextSupplierCode();
                        DataAccess.Insert(supplier, broker);
                    }
                    else
                    {
                        DataAccess.Update(supplier, broker);
                    }

                    //Save supplier contacts
                    List<MstSupplierContactEntity> insertList = new List<MstSupplierContactEntity>();
                    List<MstSupplierContactEntity> modifyList = new List<MstSupplierContactEntity>();
                    foreach (DataRow dr in dtDetail.Rows)
                    {
                        MstSupplierContactEntity entity = null;
                        switch (dr.RowState)
                        {
                            case DataRowState.Added:
                                entity = new MstSupplierContactEntity(dr);
                                insertList.Add(entity);
                                break;
                            case DataRowState.Modified:
                                entity = new MstSupplierContactEntity(dr);
                                modifyList.Add(entity);
                                break;
                            default:
                                continue;
                        }
                    }
                    DataAccess.Delete<MstSupplierContactEntity>(deleteList, broker);
                    DataAccess.Update<MstSupplierContactEntity>(modifyList, broker);
                    DataAccess.Insert<MstSupplierContactEntity>(insertList, broker);
                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
        }
        #endregion
    }
	
	
}	

